const formidable = require('formidable');
const fs = require('fs');
const path = require('path');

const { getResJson, formatTime } = require('../../assets/util');

const { HOST } = require('../../assets/config');

/**
 * 用户微信图上传
 */
exports.wechatImagesUpload = (req, res) => {
    /* 创建上传表单 */
    let form = new formidable.IncomingForm();
    form.uploadDir = './upload/wechatImages';
    uploadCommon(req, res, form);
}

/**
 * 文章封面图
 */
exports.coverImagesUpload = (req, res) => {
    let form = new formidable.IncomingForm();
    let timeDir = mkdir();
    form.uploadDir = `./upload/coverImages/${timeDir}`;
    uploadCommon(req, res, form);
}

exports.articleImagesUpload = (req, res) => {
    let form = new formidable.IncomingForm();
    let timeDir = mkdir('articleImages');
    form.uploadDir = `./upload/articleImages/${timeDir}`;
    let files = [];
    form.on('file', function(filed, file) {
        files.push(file);
    });
    form.parse(req, (err, fields) => {
        let uploadFlag = true;
        let urlData = [];
        files.map(item => {
            let oldpath = item.path;
            /* 拼接新的文件名 */
            let time = formatTime(new Date(), 'YYYYMMDDHHmmss');
            let num = Math.floor(Math.random() * 8999 + 10000);
            let imageName = `${time}_${num}.${item.name}`;
            let newpath = `${form.uploadDir}/${imageName}`;
            let result = fs.renameSync(oldpath, newpath);
            if (result) {
                uploadFlag = false;
            } else {
                let mypath = newpath.replace("./upload", `${HOST}/upload`);
                urlData.push(mypath);
            }
        })
        let resJson = {};
        if (!uploadFlag) {
            resJson = {
                errno: 1,
                data: []
            }
        } else {
            resJson = {
                errno: 0,
                data: urlData
            };
        }
        res.send(resJson);
    })
}


function uploadCommon(req, res, form) {
    /* 设置编码格式 */
    form.encoding = 'utf-8';
    form.parse(req, (err, fields, files) => {
        let oldpath = files.file.path;
        /* 拼接新的文件名 */
        let time = formatTime(new Date(), 'YYYYMMDDHHmmss');
        let num = Math.floor(Math.random() * 8999 + 10000);
        let imageName = `${time}_${num}.${files.file.name}`;
        let newpath = `${form.uploadDir}/${imageName}`;
        fs.rename(oldpath, newpath, err => {
            if (err) {
                let resJson = getResJson({}, '文件上传失败', false);
                res.send(resJson);
                return;
            }
            let mypath = newpath.replace("./upload", `${HOST}/upload`);
            let resJson = getResJson({
                path: mypath
            }, '上传成功');
            res.send(resJson);
        })
    })
}

/**
 * 创建文件夹
 * @param {String} dirname 在哪个文件夹下建
 * @return {String} timedir 创建之后的文件夹
 */
function mkdir(dirname = 'coverImages') {
    // 拿到项目根目录
    const rootpath = path.join(__dirname, '../../');
    /* 根据上传日期去区分文章封面 */
    let timeDir = formatTime(new Date(), 'YYYY-MM-DD');
    let endPath = `${rootpath}upload/${dirname}/${timeDir}`;
    // 判断是否存在该文件夹
    let isHas = fs.existsSync(endPath);
    // 如果不存在就去创建
    if (!isHas) {
        fs.mkdirSync(endPath);
        console.log(`${timeDir}文件夹创建成功`);
    }
    return timeDir;
}